<!-- AI告警督办-列表页（首页） -->
<template>
  <view class="list-all">
    <Header :title="title" bgColor="#fff"/>
    <search-box ref="searchBOX" placeholder="请输入学校名称" mode="input" :searchContent="queryForm.schoolName" @search="search" @clear="searchClear" :showSift="true"  @shiftReset="shiftReset" @shiftConfirm="shiftConfirm" :iconFlag="iconFlag">
    <template #shift class="popup-content">
        <view class="popup-title-row">
          <text>告警日期</text>
        </view>
        <view class="popup-date-row">
          <view class="date" style="width: 100%;" @click="openCalendars">{{ dateRange ? dateRange : '请选择告警日期' }}</view>
          <uv-calendars ref="calendars" allowSameDay="true" mode="range" @confirm="searchDate"></uv-calendars>
        </view>
        <view class="popup-title-row">
          <text>告警类型</text>
        </view>
        <view class="popup-con-row">
          <view v-for="(item, index) in stateTagist" :key="index" class="item"
                :class="{actived:item.value === stateTag}" @click="rectifyStateTagFun(item)">
            {{ item.label }}
          </view>
        </view>
        <view class="popup-title-row">
          <text>整改状态</text>
        </view>
        <view class="popup-con-row">
          <view v-for="(item, index) in stateList" :key="index" class="item"
                :class="{actived:item.value === state}" @click="rectifyStateFun(item)">
            {{ item.label }}
          </view>
        </view>
        <view class="popup-title-row">
          <text>督办状态</text>
        </view>
        <view class="popup-con-row">
          <view v-for="(item, index) in alarmUrgeStateList" :key="index" class="item"
                :class="{actived:item.value === alarmUrgeState}" @click="alarmUrgeStateFun(item)">
            {{ item.label }}
          </view>
        </view>
      </template>
    </search-box>
    <scroll-view :scroll-y="true" class="canteen-scroll-height"
                 refresher-enabled="true" :refresher-triggered="triggered"
                 :lower-threshold="50" @scrolltolower="nextPage"
                 :refresher-threshold="80" refresher-background="rgb(244, 244, 244)"
                 @refresherpulling="onPulling" @refresherrefresh="onRefresh"
                 @refresherrestore="onRestore" @refresherabort="onAbort"
                 refresher-default-style="none">
      <view v-if="emptyFlag" class="empty-box">
        <uv-empty mode="data" icon="/static/image/no-data.png" width="200rpx" height="260rpx" text="&nbsp;"></uv-empty>
      </view>
      <view v-else class="option-box">
        <view v-for="(item, index) in dataList" :key="item.id">
          <card-list :rowId="item.id"
                     @handleCard="handleView(item)"
                     :imageApi="true"
                     :imagePath="imageUrl(item.image)"
                     :imageTag="warningStateTagFormatter(item.stateTag)"
                     :deltaState="getDeltaState(item.alarmUrgeState)"
                     :deltaStateColor="getDeltaStateClass(item.alarmUrgeState)"
                     :imageState="getImageState(item.state)"
                     :imageStateColor="getImageStateClass(item.state)"
                     :title="item.schoolName" :labelList="['告警日期:', '预警数量:']"
                     :valueList="[dayjs(item.alarmDate).format('YYYY-MM-DD'), `${item.warnTotalNum}条`]"
                     :colorRendering="{row: [3], class: getColorClass(item.state)}"
                     :showCheckBox="true" @onCheckboxChange="onCheckboxChange"
                     :checkboxDisabled="item.alarmUrgeState=='1' || item.state=='2'">
            <template #button>
              <button class="blue-button" :disabled="(item.alarmUrgeState=='1' || item.state=='2') " @tap.stop="urgeView(item)">督办</button>
            </template>
          </card-list>
        </view>
        <uni-load-more :status="loadingType" :content-text="contentText"/>
      </view>
    </scroll-view>
    <view class="bottom-box" style="width: 100%;" @click.stop>
      <button class="sure-button" @tap.stop="toOversee">批量督办</button>
    </view>
  </view>
</template>

<script setup>
  import api from "@/api/pco/alarm/alarmInfo.js";
  import schoolApi from "@/api/school/school/school.js";
  import cardList from "@/packagePcoCheck/components/card-list/index.vue";
  import {ref} from "vue";
  import {warningStateTagFormatter} from "@/utils/formValidate";
  import dayjs from "dayjs";
  import searchBox from "@/packagePcoCheck/components/search-box/index.vue";
  import config from "@/common/config";
  import {onLoad} from "@dcloudio/uni-app";
  const {proxy} = getCurrentInstance();
  let userInfo = ref(uni.getStorageSync('userInfo'));
  let title = ref('告警督办');

  let searchBOX = ref();
  let schoolList = ref([]);
  let stateList = ref([
    {label: '待整改', value: '0'},
    {label: '部分整改', value: '1'},
    {label: '整改完成', value: '2'},
  ]);
  let stateTagist = ref([
    {label: '超期未整改', value: 'CQ'},
    {label: '预警复现', value: 'FX'},
  ]);
  let alarmUrgeStateList = ref([
    {label: '已督办', value: '1'},
    {label: '未督办', value: '0'},
  ]);

  let emptyFlag = ref(false);
  let freshing = ref(false);
  let triggered = ref(false);
  let loadingType = ref('noMore');
  let contentText = reactive({
    contentdown: "上拉显示更多",
    contentrefresh: "正在加载...",
    contentnomore: "没有更多数据了"
  });
  let dataList = reactive([]);
  let queryForm = reactive({
    pageSize: 10,
    pageNum: 1,
    state: '',
    startDate: '',
    endDate: '',
    schoolName: '',
  });
  let total = ref(0);

  /** 数据加载 */
  onLoad((option) => {
    if (option.schoolId) {
      queryForm.schoolId = option.schoolId;
    }
  });

  /** 搜索数据列表 */
  let search = (e) => {
    queryForm.schoolName= e
    queryForm.pageNum = 1;
    getListData();
  }

  /** 搜索数据列表 */
  let searchList = (e) => {
    queryForm.pageNum = 1;
    getListData();
  }

  /** 初始化 */
  let getListData = () => {
    queryForm.userId = userInfo.value.user.id
    queryForm.orgId = userInfo.value.orgId;
    console.log(queryForm)
    proxy.http.post(api.alarmList, queryForm).then(res => {
        if (res.code === 0) {
            total.value = res.data.total;
            if (queryForm.pageNum === 1) {
                dataList.length = 0;
            }
            nextTick(()=>{
              dataList.push(...res.data.records);
              if (dataList.length < total.value) {
                loadingType.value = 'more';
              } else {
                loadingType.value = 'noMore';
              }
              emptyFlag.value = dataList.length <= 0;
            })
        }
    })
  }

  let imgMinioPath = ref(config.IMG_MINIO_PATH.replace("/schoolWeb",""));
  let imageUrl = (imagePath) => {
    return imgMinioPath.value + imagePath;
  }

  let checkboxValue = ref([]);

  let onCheckboxChange = (id) => {
    if (checkboxValue.value.includes(id)) {
      checkboxValue.value = checkboxValue.value.filter(item => item !== id);
    } else {
      checkboxValue.value.push(id);
    }
  }

  let toOversee = () => {
    if (checkboxValue.value.length > 0) {
      batchOversee()
    } else {
      uni.showToast({
        icon: 'none',
        title: '请至少选择一条预警数据'
      });
      return;
    }
  }

  // 批量督办
  let batchOversee = () => {
    uni.navigateTo({
      url: '/packagePcoCheck/pages/alarmInfo/batchOverseeForm?ids=' + JSON.stringify(checkboxValue.value),
      success: () => {
        uni.$once("refresh", (data) => {
          checkboxValue.value = [];
        });
      },
    });
  }

  let handleView = (item) => {
    uni.navigateTo({
      url: `/packagePcoCheck/pages/alarmInfo/baseInfo?id=${item.id}&urgeShow=1`
    });
  }
  let urgeView = (item) => {
    uni.navigateTo({
      url: `/packagePcoCheck/pages/alarmInfo/baseInfo?id=${item.id}&urgeShow=0`
    });
  }

  let getSchoolList = () => {
    proxy.http.post(schoolApi.getOrgSchoolNoTenantId, {}).then(res => {
      if (res.code === 0) {
        schoolList.value = res.data;
        schoolList.value.unshift({
          id: '',
          name: '全部'
        })
      }
    })
  }

  /** 搜索-日期 */
  let dateChange = (e) => {
    queryForm.startDate = e;
    queryForm.endDate = e;
    searchList();
  }
  /** 滚动视图区域 */
  /** 翻页 */
  let nextPage = (e) => {
    if (queryForm.pageNum * queryForm.pageSize < total.value) {
      queryForm.pageNum++;
      getListData()
    }
  }
  /** 下拉 */
  let onPulling = (e) => {
    freshing.value = false;
    setTimeout(() => {
      triggered.value = true;
    }, 1000)
  }
  /** 刷新 */
  let onRefresh = (e) => {
    if (freshing.value) return;
    triggered.value = 'restore';
    setTimeout(() => {
      freshing.value = false;
      triggered.value = false;
    }, 1000)
    //获取数据的函数
    queryForm.pageNum = 1 // 记录数
    getListData()
  }
  let onRestore = (e) => {
    triggered.value = 'restore'; // 需要重置
  }
  let onAbort = (e) => {}
  let popup = ref();
  let loading = ref(false);

  onShow(() => {
    checkboxValue.value = []
    searchList();
    getSchoolList();
  })

  function getDeltaState (alarmUrgeState) {
    if (alarmUrgeState === '1') {
      return '已督';
    } else {
      return '未督';
    }
  }

  function getDeltaStateClass (alarmUrgeState) {
    if (alarmUrgeState === '1') {
      return 'blue';
    } else {
      return 'info';
    }
  }

  function getImageState (state) {
    if (state === '0') {
      return '待整改';
    } else if (state === '1') {
      return '部分整改';
    } else if (state === '2') {
      return '整改完成';
    }
  }

  function getImageStateClass (state) {
    if (state === '0') {
      return 'red';
    } else if (state === '1') {
      return 'yellow';
    } else if (state === '2') {
      return 'green';
    }
  }

  function getColorClass (state) {
    if (state === '0') {
      return 'red';
    } else if (state === '1') {
      return 'yellow';
    } else if (state === '2') {
      return 'green';
    }
  }

  // 弹出时间选择
  let calendars = ref();
  let openCalendars = (e) => {
    calendars.value.open();
  }
  // 搜索
  let dateRange = ref();

  let searchDate = (e) => {
    queryForm.startDate = e.range.before;
    queryForm.endDate = e.range.after;
    dateRange.value=queryForm.startDate+"~"+queryForm.endDate
  }
  // 清空
  let searchClear = () => {
    queryForm.schoolName = '';
    searchList();
  }

  // 筛选 整改状态
  const state = ref('');
  const rectifyStateFun = (item) => {
    if (state.value === item.value) {
      state.value = '';
    } else {
      state.value = item.value;
    }
  };

  // 筛选 告警状态
  const stateTag = ref('');
  const rectifyStateTagFun = (item) => {
    if (stateTag.value === item.value) {
      stateTag.value = '';
    } else {
      stateTag.value = item.value;
    }
  }
  // 筛选 告警状态
  const alarmUrgeState = ref('');
  const alarmUrgeStateFun = (item) => {
    if (alarmUrgeState.value === item.value) {
      alarmUrgeState.value = '';
    } else {
      alarmUrgeState.value = item.value;
    }
  }


  // 筛选重置
  let shiftReset = (e) => {
    state.value = '';
    stateTag.value = '';
    alarmUrgeState.value = '';
    queryForm.state = '';
    queryForm.stateTag = '';
    queryForm.startDate = '';
    queryForm.endDate = '';
    queryForm.alarmUrgeState = '';
    dateRange.value= '';
    changeIcon();
    searchList();
  }

  // 筛选确认
  let shiftConfirm = (e) => {
    queryForm.state = state.value;
    queryForm.stateTag = stateTag.value;
    queryForm.alarmUrgeState= alarmUrgeState.value;
    changeIcon();
    searchList();
  }

  let iconFlag = ref(false);
  let changeIcon = () => {
     iconFlag.value = !!(queryForm.startDate || queryForm.endDate || queryForm.state || queryForm.stateTag || queryForm.alarmUrgeState );
  }

</script>

<style scoped lang="scss">
  @import '@/static/css/dailycheck/common.scss';

  .list-all {
    margin: 0;
  }

  .bottom-item {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    height: 100%;
    margin: 24rpx auto;
  }

  .r-button {
    background-color: #3775F6 !important;
    border: 1px solid #3775F6;
    color: #fff !important;
    width: 30%;
  }

  .scroll-height {
    background: #f6f6f6;
    height: calc(100vh - 440rpx);
  }

  .canteen-scroll-height {
    background: #f6f6f6;
    height: calc(100vh - 440rpx);
  }

  ::v-deep .uv-button--hairline {
    border-radius: 15rpx;
    height: 70rpx;
  }

  .areaWidth {
    position: relative;
    margin: 30rpx 0;
    width: 100%;

    ::v-deep .uv-textarea__field {
      text-align: left !important;
      padding: 10px !important;
    }
  }

  .popup-box {
    width: 100vw;
  }

  .popup-content {
    padding: 20rpx;
  }

  ::v-deep .uv-tabs__wrapper {
    background: #f6f6f6;
  }
  .popup-con-row{
    margin-bottom: 30rpx;
  }
</style>


